//
//  LoginLogicController.m
//  CKApp
//
//  Created by CC on 2020/8/26.
//  Copyright © 2020 This Moment. All rights reserved.
//

#import "LoginLogicController.h"
#import "CCNavigationController.h"
#import "LcFoundation.h"
#import "JVERIFICATIONService.h"
#import "CKLoadingView.h"
#import "LoginViewController.h"
#import "OnceLoginRequestData.h"
#import "OnceLoginResponseData.h"
#import "UserManager.h"
#import "ApiRequestUtil.h"

@interface LoginLogicController ()
@property(nonatomic, strong) LoginComleteHandler completeBlock;
@property(nonatomic, strong) JVUIConfig* config;
@property(nonatomic, weak) BaseViewController* fromView;
@property(nonatomic, weak) UIView* customView;
@end

@implementation LoginLogicController

- (void)showVerifyOrLoginFromViewCtrl:(BaseViewController*)viewCtrl
                        completeBlock:(LoginComleteHandler)completeBlock {
  self.fromView = viewCtrl;
  self.completeBlock = completeBlock;
  if ([JVERIFICATIONService checkVerifyEnable]) {
    LcWeakSelf;
    [JVERIFICATIONService preLogin:1000
                        completion:^(NSDictionary* result) {
                          LcStrongSelf;
                          NSInteger resultCode = [result[@"resultCode"] integerValue];
                          if (resultCode == 0) {
                            [self customUI];
                            [JVERIFICATIONService
                                getAuthorizationWithController:viewCtrl
                                                          hide:NO
                                                    completion:^(NSDictionary* result) {
                                                      NSString* token = result[@"loginToken"];
                                                      NSInteger code =
                                                          [result[@"code"] integerValue];
                                                      if (token && code == 6000) {
                                                        [self requestLogin:token];
                                                      } else {
                                                        [self showLoginViewCtrl];
                                                      }
                                                    }];
                          } else {
                            [self showLoginViewCtrl];
                          }
                        }];
  } else {
    [self showLoginViewCtrl];
  }
}

- (void)showLoginViewCtrl {
  LoginViewController* viewCtrl = [[LoginViewController alloc] init];
  CCNavigationController* nav = [[CCNavigationController alloc] initWithRootViewController:viewCtrl];
  [self.fromView presentTransparentViewController:nav animated:YES completion:nil];
}

- (void)customUI {
  JVUIConfig* config = [[JVUIConfig alloc] init];
  self.config = config;
  config.navReturnImg = [UIImage imageNamed:@"navbar_close"];
  config.agreementNavReturnImage = [UIImage imageNamed:@"navbar_close"];
  config.autoLayout = YES;
  config.shouldAutorotate = NO;
  config.navText = nil;
  config.navDividingLineHidden = YES;
  config.prefersStatusBarHidden = NO;
  config.navColor = [UIColor whiteColor];

  // logo
  config.logoImg = [UIImage imageNamed:@"logo_login"];
  CGFloat logoWidth = 90;
  CGFloat logoHeight = logoWidth;
  JVLayoutConstraint* logoConstraintX =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeCenterX
                                       multiplier:1
                                         constant:0];
  JVLayoutConstraint* logoConstraintY =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeTop
                                       multiplier:1
                                         constant:76];
  JVLayoutConstraint* logoConstraintW =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeWidth
                                       multiplier:1
                                         constant:logoWidth];
  JVLayoutConstraint* logoConstraintH =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeHeight
                                       multiplier:1
                                         constant:logoHeight];
  config.logoConstraints = @[ logoConstraintX, logoConstraintY, logoConstraintW, logoConstraintH ];

  //号码栏
  JVLayoutConstraint* numberConstraintX =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeCenterX
                                       multiplier:1
                                         constant:0];
  JVLayoutConstraint* numberConstraintY =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemLogo
                                        attribute:NSLayoutAttributeBottom
                                       multiplier:1
                                         constant:16];
  JVLayoutConstraint* numberConstraintW =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeWidth
                                       multiplier:1
                                         constant:130];
  JVLayoutConstraint* numberConstraintH =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeHeight
                                       multiplier:1
                                         constant:25];

  config.numberConstraints =
      @[ numberConstraintX, numberConstraintY, numberConstraintW, numberConstraintH ];

  // slogan展示
  JVLayoutConstraint* sloganConstraintX =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeCenterX
                                       multiplier:1
                                         constant:0];
  JVLayoutConstraint* sloganConstraintY =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNumber
                                        attribute:NSLayoutAttributeBottom
                                       multiplier:1
                                         constant:8];
  JVLayoutConstraint* sloganConstraintW =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeWidth
                                       multiplier:1
                                         constant:130];
  JVLayoutConstraint* sloganConstraintH =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeHeight
                                       multiplier:1
                                         constant:20];

  config.sloganConstraints =
      @[ sloganConstraintX, sloganConstraintY, sloganConstraintW, sloganConstraintH ];

  //登录按钮
  UIImage* login_nor_image = [UIImage imageNamed:@"login_btn_normal"];
  UIImage* login_dis_image = [UIImage imageNamed:@"login_btn_disable"];
  UIImage* login_hig_image = [UIImage imageNamed:@"login_btn_normal"];
  if (login_nor_image && login_dis_image && login_hig_image) {
    config.logBtnImgs = @[ login_nor_image, login_dis_image, login_hig_image ];
  }
  config.logBtnText = @"点击登录";
  CGFloat loginButtonWidth = LcUIUtility.screenWidth - 80.0;
  CGFloat loginButtonHeight = 44;
  JVLayoutConstraint* loginConstraintX =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeCenterX
                                       multiplier:1
                                         constant:0];
  JVLayoutConstraint* loginConstraintY =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSlogan
                                        attribute:NSLayoutAttributeBottom
                                       multiplier:1
                                         constant:22];
  JVLayoutConstraint* loginConstraintW =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeWidth
                                       multiplier:1
                                         constant:loginButtonWidth];
  JVLayoutConstraint* loginConstraintH =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeHeight
                                       multiplier:1
                                         constant:loginButtonHeight];
  config.logBtnConstraints =
      @[ loginConstraintX, loginConstraintY, loginConstraintW, loginConstraintH ];

  //隐私
  config.agreementNavBackgroundColor = [UIColor clearColor];
  config.agreementNavText = nil;
  config.privacyState = YES;
  config.privacyTextFontSize = 12;
  config.privacyTextAlignment = NSTextAlignmentCenter;
  config.appPrivacyOne = @[ @"用户协议", @"https://www.jiguang.cn/about" ];
  config.appPrivacyTwo = @[ @"隐私条款", @"https://www.jiguang.cn/about" ];
  config.privacyComponents = @[
    @"登录即同意《", @"》、《", @"》和《", @"》"
                                                       @"并使用本机号码登"
                                                       @"录"
  ];
  config.appPrivacyColor = @[ LC_COLOR_GRAY, LC_COLOR_GRAY ];

  CGFloat privacyWidth = LcUIUtility.screenWidth - 50.0;

  JVLayoutConstraint* privacyConstraintX =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeCenterX
                                       multiplier:1
                                         constant:0];
  JVLayoutConstraint* privacyConstraintW =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth
                                        relatedBy:NSLayoutRelationGreaterThanOrEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeWidth
                                       multiplier:1
                                         constant:privacyWidth];

  JVLayoutConstraint* privacyConstraintY =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeBottom
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeBottom
                                       multiplier:1
                                         constant:-25];
  JVLayoutConstraint* privacyConstraintH =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeHeight
                                       multiplier:1
                                         constant:40];

  config.privacyConstraints =
      @[ privacyConstraintX, privacyConstraintW, privacyConstraintY, privacyConstraintH ];

  JVLayoutConstraint* privacyConstraintY1 =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeBottom
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeBottom
                                       multiplier:1
                                         constant:-16];

  config.privacyHorizontalConstraints =
      @[ privacyConstraintX, privacyConstraintW, privacyConstraintH, privacyConstraintY1 ];

  //勾选框
  UIImage* uncheckedImg = [UIImage imageNamed:@"control_checkbox"];
  UIImage* checkedImg = [UIImage imageNamed:@"control_checkbox_s"];
  CGFloat checkViewWidth = 20;
  CGFloat checkViewHeight = 20;

  config.uncheckedImg = uncheckedImg;
  config.checkedImg = checkedImg;

  JVLayoutConstraint* checkViewConstraintX =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeLeft
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeLeft
                                       multiplier:1
                                         constant:10];

  JVLayoutConstraint* checkViewConstraintY =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeTop
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemPrivacy
                                        attribute:NSLayoutAttributeTop
                                       multiplier:1
                                         constant:2];

  JVLayoutConstraint* checkViewConstraintW =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeWidth
                                       multiplier:1
                                         constant:checkViewWidth];
  JVLayoutConstraint* checkViewConstraintH =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeHeight
                                       multiplier:1
                                         constant:checkViewHeight];
  config.checkViewConstraints =
      @[ checkViewConstraintX, checkViewConstraintY, checkViewConstraintW, checkViewConstraintH ];

  // loading
  JVLayoutConstraint* loadingConstraintX =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterX
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeCenterX
                                       multiplier:1
                                         constant:0];
  JVLayoutConstraint* loadingConstraintY =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeCenterY
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemSuper
                                        attribute:NSLayoutAttributeCenterY
                                       multiplier:1
                                         constant:0];
  JVLayoutConstraint* loadingConstraintW =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeWidth
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeWidth
                                       multiplier:1
                                         constant:30];
  JVLayoutConstraint* loadingConstraintH =
      [JVLayoutConstraint constraintWithAttribute:NSLayoutAttributeHeight
                                        relatedBy:NSLayoutRelationEqual
                                           toItem:JVLayoutItemNone
                                        attribute:NSLayoutAttributeHeight
                                       multiplier:1
                                         constant:30];
  config.loadingConstraints =
      @[ loadingConstraintX, loadingConstraintY, loadingConstraintW, loadingConstraintH ];

  config.customLoadingViewBlock = ^(UIView* View) {
    CKLoadingView* loadingView = [CKLoadingView loadFromBundle];
    [View addSubview:loadingView];
    [loadingView startAnimating];
  };

  [JVERIFICATIONService customUIWithConfig:config
                               customViews:^(UIView* customAreaView) {
                                 self.customView = customAreaView;
                                 [self caculateCustomUIFrame];
                               }];
}

- (void)caculateCustomUIFrame {
  if (!self.customView) {
    return;
  }

  UIButton* otherButton = [UIButton buttonWithType:UIButtonTypeCustom];
  [otherButton setWhiteStyle];
  [otherButton setLcFont:[LcFont sgr12]];
  [otherButton setTitle:@"使用其他手机号码登录"];
  [otherButton setFrame:CGRectMake(40, 320, LcUIUtility.screenWidth - 80.0, 44.0)];
  [otherButton addTarget:self
                  action:@selector(otherLogin)
        forControlEvents:UIControlEventTouchUpInside];
  [self.customView addSubview:otherButton];
}

- (void)otherLogin {
  [JVERIFICATIONService dismissLoginControllerAnimated:YES
                                            completion:^{
                                              [self showLoginViewCtrl];
                                            }];
}

#pragma mark - RequestData
- (void)requestLogin:(NSString*)loginToken {
  OnceLoginRequestData* requestData = [[OnceLoginRequestData alloc] initWithLoginToken:loginToken];
  [ApiRequestUtil sendRequest:requestData
      successHandler:^(__kindof CCRequestData* requestData, OnceLoginResponseData* responseData) {
        [[UserManager sharedInstance] didLogin:responseData.data.info
                                   clientToken:responseData.data.user_session_id];
        [JVERIFICATIONService dismissLoginControllerAnimated:YES
                                                  completion:^{
                                                    if (self.completeBlock != nil) {
                                                      self.completeBlock(YES);
                                                    }
                                                  }];
      }
      errorHandler:^(__kindof CCRequestData* requestData, LcApiError* apiError) {

      }
      showModalLoadingIndicator:YES];
}

@end
